import { DirectiveBinding } from 'vue';


function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const { value } = binding;

  if (Array.isArray(value)) {
    if (value.length > 0) {
      const permissionValues = value;
      let userPermission = [];
      if (localStorage.getItem('permissionList')) {
        userPermission = JSON.parse(localStorage.getItem('permissionList') as string);
      }

      // @ts-ignore
      const hasPermission = userPermission
        ? // @ts-ignore
          userPermission.includes(...permissionValues)
        : false;

      if (!hasPermission && el.parentNode) {
        el.parentNode.removeChild(el);
      }
    }
  } else {
    throw new Error(`need roles! Like v-auto="['admin','user']"`);
  }
}

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding);
  },
};
